import type { EChartsOption, EChartsType, SeriesOption, TooltipComponentOption } from 'echarts'

import * as echarts from 'echarts'
export const defaultTooltipStyle = {
  backgroundColor: '#0005',
  borderColor: '#0005',
  textStyle: {
    color: '#fff',
    fontStyle: 'normal',
    fontFamily: 'D-DIN-PRO-500-Medium',
    fontSize: 12
  }
} as TooltipComponentOption
export class useEcharts {
  chart: echarts.ECharts | null = null
  constructor(
    dom: HTMLElement,
    option: EChartsOption,
    callback?: (data: { name: string; value: any; seriesName: string }) => void,
    scroll: boolean = false
  ) {
    this.initChart(dom, option, scroll, callback)
  }
  initChart(
    dom: HTMLElement,
    option: EChartsOption,
    scroll: boolean,
    callback?: (data: { name: string; value: any; seriesName: string }) => void
  ) {
    if (!this.chart) {
      this.chart = echarts.init(dom, null, { renderer: 'svg' })
      window.addEventListener('resize', () => {
        this.chart && this.chart.resize()
      })
    }
    this.setOption(option)
    this.chart.on('click', (params) => {
      if (callback) {
        callback({ name: params.name, value: params.value, seriesName: params.seriesName ?? '' })
      }
    })

    // this.chart.on('mouseover', (params) => {
    //   console.log(params);
    // })

    if (scroll) {
      const dataLength = (option.series as SeriesOption[])[0].data as any[]
      this.carouselFn(dataLength.length, 2000)
    }
  }
  setOption(option: EChartsOption) {
    if (this.chart) {
      if (option) this.chart.setOption(option)
    }
  }
  interval: null | number = null
  /**
   *
   * @param lth 配置项
   * @param this.chart 图表实例
   * @param t 滚动延时
   * @param endValue 一次几个
   */
  carouselFn(lth: number, tm: number) {
    if (!this.chart) return
    // this.SetValue(lth, tm)

    this.chart.on('mouseover', () => {
      // 鼠标悬浮，停止自动轮播
      this.SetValue(lth, tm)
    })

    this.chart.on('mouseout', () => {
      // 鼠标移出，重新开始自动轮播
      if (this.interval) clearInterval(this.interval)
    })
  }
  SetValue(dataLen: number, tm: number = 2000) {
    let currentIndex = -1
    if (this.interval) {
      clearInterval(this.interval)
      this.interval = null
    }
    this.interval = setInterval(() => {
      if (!this.chart) return
      // 取消之前高亮的图形
      this.chart.dispatchAction({
        type: 'downplay',
        seriesIndex: 0,
        dataIndex: currentIndex
      })
      currentIndex = (currentIndex + 1) % dataLen
      // 高亮当前图形
      this.chart.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: currentIndex
      })
      // 显示 tooltip
      this.chart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: currentIndex
      })
    }, tm)
  }
}
